package dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import utils.MyDataSourceUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

public class TransferDao {

    public void out(int out, double money) {
        try {
        QueryRunner runner = new QueryRunner();
        Connection conn = MyDataSourceUtils.getCurrentConnection();
        String sql = "update account set money=money-? where id = ?";
            runner.update(conn,sql,money,out);
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    public void in(int in, double money) {
        try {
        QueryRunner runner = new QueryRunner();
        Connection conn = MyDataSourceUtils.getCurrentConnection();
        String sql = "update account set money=money+? where id = ?";
            runner.update(conn,sql,money,in);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean balance(Connection conn,double money,int out) {
        QueryRunner runner = new QueryRunner();
        String sql = "select * from account where id =? ";
        boolean is = true;
        try {
            Map<String ,Object> map = runner.query(conn,sql,new MapHandler(),out);
            for (String key : map.keySet()){

                if (key == "money"){
                    Double mon = (Double) map.get(key);
                    if (mon < money){
                        is = false;
                    }
                }
            }
        } catch (SQLException e) {
            is = false ;
            e.printStackTrace();
        }
    return is;
    }
}
